import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

let baseUrl = "localhost:3000/api/v1";

const router = useRouter();

if (process.env.NODE_ENV === "production") {
  baseUrl = "localhost:3000/api/v1";
}

const httpClient = axios.create({
  baseURL: `http://${baseUrl}`,
  timeout: 10000,
  headers: { "X-Custom-Header": "foobar" },
});

// 添加请求拦截器
httpClient.interceptors.request.use(
  async (config) => {
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["Authorization"] = `Bearer ${localStorage.getItem("token")}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
httpClient.interceptors.response.use(
  async (response) => {
    return response;
  },
  async (error) => {
    if (error.response.status === 401) {
      localStorage.removeItem("token");
      router.push("/#/auth?type=login");
    } else if (error.response.status === 500) {
      ElMessage({
        type: "info",
        message: `服务端错误，请稍后再试`,
        offset: 80,
      });
    }
    return Promise.reject(error);
  }
);

export default httpClient;
